package com.zhiyizhen.handheld.component.message.view;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

public class AboveAnchorPopupHelper {
    /**
     * 显示一个位于锚点View正上方的PopupWindow
     * @param context 上下文
     * @param anchor 锚点View
     * @param layoutResId PopupWindow的布局资源ID
     * @return 显示的PopupWindow实例
     */
    public static PopupWindow showAboveAnchor(Context context, View anchor, int layoutResId) {
        // 加载PopupWindow的布局
        View contentView = LayoutInflater.from(context).inflate(layoutResId, null);

        // 创建PopupWindow
        PopupWindow popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true // 可点击
        );

        // 计算PopupWindow的位置
        calculateAndShowPopup(popupWindow, anchor, contentView);

        return popupWindow;
    }

    /**
     * 计算并显示PopupWindow在锚点正上方
     */
    private static void calculateAndShowPopup(PopupWindow popupWindow, View anchor, View contentView) {
        // 测量contentView以获取其宽高
        contentView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight = contentView.getMeasuredHeight();

        // 获取锚点View在屏幕上的位置
        int[] anchorLocation = new int[2];
        anchor.getLocationOnScreen(anchorLocation);
        int anchorX = anchorLocation[0];
        int anchorY = anchorLocation[1];

        // 获取锚点View自身的宽高
        int anchorWidth = anchor.getWidth();
        int anchorHeight = anchor.getHeight();

        // 计算PopupWindow的x坐标（使其水平居中于锚点）
        int popupX = anchorX + (anchorWidth - popupWidth) / 2;

        // 计算PopupWindow的y坐标（使其底部与锚点顶部对齐）
        int popupY = anchorY - popupHeight;

        // 显示PopupWindow
        popupWindow.showAtLocation(
                anchor,
                Gravity.NO_GRAVITY, // 不使用重力，完全靠计算的坐标定位
                popupX,
                popupY
        );
    }
}
